package com.phiture.erp.common.utils;

import com.phiture.erp.basic.api.pojo.resp.ErpUserCustomizeConfigResp;
import com.phiture.erp.basic.api.service.ErpUserCustomizeConfigApi;
import com.phiture.erp.common.constants.ErpUserCustomizeConfigKeyConstants;
import com.phiture.erp.common.constants.RedisKeyConstants;
import org.redisson.api.RAtomicLong;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author YH
 * @date 2025/4/8
 */

@Component
public class ErpNoGenerator {
    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private ErpUserCustomizeConfigApi userCustomizeConfigApi;

    private static final DateTimeFormatter PURE_DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
    public String generate(String prefix) {
        String dateStr = LocalDateTime.now().format(PURE_DATE_FORMATTER);
        String redisKey = RedisKeyConstants.NO + prefix + dateStr;

        RAtomicLong atomicLong = redissonClient.getAtomicLong(redisKey);
        long sequenceNo = atomicLong.incrementAndGet(); // 递增并获取新值
        atomicLong.expire(Duration.ofDays(1));

        // 生成订单号（如：SO202404010001）
        // 获取系统设置的序号位数
        ErpUserCustomizeConfigResp sequenceLength = userCustomizeConfigApi.getUserCustomizeConfig(ErpUserCustomizeConfigKeyConstants.ERP_SEQ_GENERATOR_LENGTH);
        // 根据系统设置的序号位数，格式化序号
        sequenceLength = sequenceLength == null ? new ErpUserCustomizeConfigResp().setConfigValue("4") : sequenceLength;
        String sequenceStr = String.format("%0" + sequenceLength.getConfigValue() + "d", sequenceNo);
        return prefix + dateStr + sequenceStr;
    }
}
